// myservice.cpp

//#include "NTServApp.h"
#include <Windows.h>
#include <tchar.h>
#include "BasicMyService.h"

namespace utility
{
	BasicMyService::BasicMyService()
		:BasicNTService(_T("NT Service Demonstration"))
	{
		m_iStartParam = 0;
		m_iIncParam = 1;
		m_iState = m_iStartParam;
	}

	BOOL BasicMyService::OnInit()
	{
		// Read the registry parameters
		// Try opening the registry key:
		// HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\<AppName>\Parameters
		HKEY hkey;
		TCHAR szKey[1024];
		_tcscpy(szKey, _T("SYSTEM\\CurrentControlSet\\Services\\"));
		_tcscat(szKey, m_szServiceName);
		_tcscat(szKey, _T("\\Parameters"));
		if (RegOpenKeyEx(HKEY_LOCAL_MACHINE,
			szKey,
			0,
			KEY_QUERY_VALUE,
			&hkey) == ERROR_SUCCESS) {
				// Yes we are installed
				DWORD dwType = 0;
				DWORD dwSize = sizeof(m_iStartParam);
				RegQueryValueEx(hkey,
					_T("Start"),
					NULL,
					&dwType,
					(BYTE*)&m_iStartParam,
					&dwSize);
				dwSize = sizeof(m_iIncParam);
				RegQueryValueEx(hkey,
					_T("Inc"),
					NULL,
					&dwType,
					(BYTE*)&m_iIncParam,
					&dwSize);
				RegCloseKey(hkey);
		}

		// Set the initial state
		m_iState = m_iStartParam;

		return TRUE;
	}

	void BasicMyService::Run()
	{
		while (m_bIsRunning) {

			// Sleep for a while
			DebugMsg(_T("My service is sleeping (%lu)..."), m_iState);
			Sleep(1000);

			// Update the current state
			m_iState += m_iIncParam;
		}
	}

	// Process user control requests
	BOOL BasicMyService::OnUserControl(DWORD dwOpcode)
	{
		switch (dwOpcode) {
	case SERVICE_CONTROL_USER + 0:

		// Save the current status in the registry
		SaveStatus();
		return TRUE;

	default:
		break;
		}
		return FALSE; // say not handled
	}

	// Save the current status in the registry
	void BasicMyService::SaveStatus()
	{
		DebugMsg(_T("Saving current status"));
		// Try opening the registry key:
		// HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\<AppName>\...
		HKEY hkey = NULL;
		TCHAR szKey[1024];
		_tcscpy(szKey, _T("SYSTEM\\CurrentControlSet\\Services\\"));
		_tcscat(szKey, m_szServiceName);
		_tcscat(szKey, _T("\\Status"));
		DWORD dwDisp;
		DWORD dwErr;
		DebugMsg(_T("Creating key: %s"), szKey);
		dwErr = RegCreateKeyEx(	HKEY_LOCAL_MACHINE,
			szKey,
			0,
			_T(""),
			REG_OPTION_NON_VOLATILE,
			KEY_WRITE,
			NULL,
			&hkey,
			&dwDisp);
		if (dwErr != ERROR_SUCCESS) {
			DebugMsg(_T("Failed to create Status key (%lu)"), dwErr);
			return;
		}	

		// Set the registry values
		DebugMsg(_T("Saving 'Current' as %ld"), m_iState); 
		RegSetValueEx(hkey,
			_T("Current"),
			0,
			REG_DWORD,
			(BYTE*)&m_iState,
			sizeof(m_iState));


		// Finished with key
		RegCloseKey(hkey);

	}

}
